package cn.vire.electric.simulation.utils;

import cn.vire.electric.simulation.pojo.LoginUserDto;
import com.alibaba.fastjson.JSONObject;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.io.UnsupportedEncodingException;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * jwt工具类
 */
public class JwtHelper {


    public static final String SECRET = "JKKLJOoasdlfj";

    public static final int calendarField = Calendar.DATE;

    public static final int calendarInterval = 7;

    public static final String CLAIM_USERINFO = "userInfo";

    /**
     * 验证token
     *
     * @param token
     * @return
     * @throws Exception
     */
    public static Map<String, Claim> verifyToken(String token) {
        DecodedJWT jwt = null;
        try {
            JWTVerifier verifier = JWT.require(Algorithm.HMAC256(SECRET)).build();
            jwt = verifier.verify(token);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return jwt.getClaims();
    }

    public static LoginUserDto getUserInfo(String token) {
        Map<String, Claim> claims = verifyToken(token);
        Claim userId_claim = claims.get(CLAIM_USERINFO);
        return JSONObject.parseObject(userId_claim.asString(), LoginUserDto.class);
    }

    /**
     * 创建token
     * @throws Exception
     */
    public static String createToken(LoginUserDto loginUserDto) {
        Date iatDate = new Date();
        Calendar nowTime = Calendar.getInstance();
        nowTime.add(calendarField, calendarInterval);
        Date expiresDate = nowTime.getTime();
        Map<String, Object> map = new HashMap<>();
        map.put("alg", "HS256");
        map.put("typ", "JWT");
        String token = null;
        try {
            token = JWT.create().withHeader(map) // header
                    .withClaim("iss", "Service") // payload
                    .withClaim("aud", "APP")
                    .withClaim(CLAIM_USERINFO, JSONObject.toJSONString(loginUserDto))
                    .withIssuedAt(iatDate)
                    .withExpiresAt(expiresDate)
                    .sign(Algorithm.HMAC256(SECRET));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return token;
    }

}

